import 'dart:io';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:hm_show_flutter/utils/permission_util.dart';
import 'package:path_provider/path_provider.dart';
import 'package:open_file/open_file.dart';
import 'package:permission_handler/permission_handler.dart';

///版本升级
class VersionUpgrade {
  static String apkName;
  String _downloadUrl;
  static String taskId;

// 获取apk存放地址(外部路径)
  static Future<String> get _apkLocalPath async {
    final directory = await getExternalStorageDirectory();
    return directory.path;
  }

  /// 下载
  Future<void> executeDownload(String name,String url) async {
    apkName = name;
    PermissionUtil.checkStoragePermission().then((isGranted) {
      if (isGranted) {
        //有权限
        download(url);
      }
    });
  }

  Future<void> download(String url) async {
    _downloadUrl = url;
    final path = await _apkLocalPath;
    apkName = apkName+'.apk';
    File file = File(path + '/' + apkName);
    if (await file.exists()) await file.delete();

    //下载
    taskId = await FlutterDownloader.enqueue(
        url: _downloadUrl,
        savedDir: path,
        fileName: apkName,
        showNotification: true,
        openFileFromNotification: true);
    FlutterDownloader.registerCallback(_downloadCallback);
  }

  static void _downloadCallback (String id, DownloadTaskStatus status, int progress) async{
    // 当下载完成时，调用安装
      if (status == DownloadTaskStatus.complete) {
        print("下载完成");
        String path = await _apkLocalPath;
        await OpenFile.open(path +"/"+ apkName);
//        FlutterDownloader.open(taskId: id);
      } else if (status == DownloadTaskStatus.running) {
          print("下载进度：" + String.fromCharCode(progress));
    }
  }

  ///安装app
   Future<Null> _installApk() async {

  }
}
